package com.huynhchihieu.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.huynhchihieu.domain.Role;

@Repository
public class RoleDAOImpl implements RoleDAO {

	// @Autowired
	// private SessionFactory sessionFactory;

	@PersistenceContext(unitName="persistenceUnit")
	private EntityManager entityManager;
	
	@Autowired
	private SessionFactory sessionFactory;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public Role getRole(int id) {
		// Role role = (Role) getCurrentSession().load(Role.class, id);
		List<Role> listRole = new ArrayList<Role>();
		listRole = entityManager.createNativeQuery("select *from role where role_id=?", Role.class).setParameter(1, id).getResultList();
		if (listRole.size() > 0) {
			return listRole.get(0);
		}
		return null;
	}
	// test sessionFactory
	public Role getRoleBySessionFactory(int id){
		List<Role> listRole = sessionFactory.getCurrentSession().createQuery("from Role").list();
		if (listRole.size() > 0) {
			return listRole.get(0);
		}
		return null;
	}

	public List<Role> getRoles() {
		return	entityManager.createNativeQuery("select * from role", Role.class).getResultList();
	}

}
